package DMSXL._2024.BinaryTrees;

public class constructMaximumBinaryTree {
    public static void main(String[] args) {

    }
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return findNode(nums,0,nums.length);
    }
    public TreeNode findNode(int[] nums, int left, int right){
        if(left >= right){
            return null;
        }
        //找到最大值的下标
        int index = findMax(nums,left,right);
        TreeNode root = new TreeNode(nums[index]);
        //分割为左右两个子树
        root.left = findNode(nums, left, index);
        root.right = findNode(nums,index + 1,right);
        //返回根节点
        return root;

    }
    public int findMax (int[] nums, int left, int right){
        int max = Integer.MIN_VALUE;
        int index = 0;
        for (int i = left;  i < right ; i++) {
            if(nums[i] > max){
                max = nums[i];
                index = i;
            }
        }
        return index;
    }
}
